package com.crazy.bookstore.common;

import com.crazy.bookstore.exception.ExceptionEnum;
import lombok.Data;

/**
 * @author: 卢辉宇
 * @date: 2022/12/27 13:42
 * @description: 统一返回对象泛型类
 */
@Data
public class ApiRestResponse <T>{
    private Integer code;
    private String msg;
    private T data;

    //定义两个常量
    private static final int OK_CODE=10000;
    private static final String OK_MSG="SUCCESS";

    /*分别创建3、2、0个的构造方法*/
    public ApiRestResponse(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public ApiRestResponse(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public ApiRestResponse() {
        this(OK_CODE,OK_MSG);
    }

    /*编写成功时调用的方法*/
    public static <T> ApiRestResponse<T> seccess(){
        return new ApiRestResponse<>();
    }

    /**
     * 重载成功返回的静态方法，此方法带参，返回有data数据
     * @param result
     * @param <T>
     * @return
     */
    public static <T> ApiRestResponse<T> seccess(T result){
        ApiRestResponse<T> response = new ApiRestResponse<>();
        response.setData(result); //把result放入data中
        return response;
    }

    /*编写失败时调用的方法*/
    public static <T> ApiRestResponse<T> error(Integer code, String msg){
        ApiRestResponse<T> response = new ApiRestResponse<>(code, msg);
        return response;
    }


    /**
     * 重载返回失败的静态方法，此方法调用的是枚举类的信息，后续更容易编写...
     * @param ex
     * @param <T>
     * @return
     */
    public static <T> ApiRestResponse<T> error(ExceptionEnum ex){
        ApiRestResponse<T> response =  new ApiRestResponse<>(ex.getCode(), ex.getMsg());
        return response;
    }
}
